package service;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/haha")
public class ClassGender_Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Class_GenderS>   stats=getClass_Gender();

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(stats);

        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write(json);

    }
private List<Class_GenderS> getClass_Gender(){
        List<Class_GenderS> stats= new ArrayList<>();
    String url = "jdbc:mysql://192.168.244.11:3306/stats?serverTimezone=Asia/Shanghai&useSSL=false";
    String user = "root";
    String password = "123456";
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    try (Connection conn = DriverManager.getConnection(url, user, password);
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery(" SELECT class_id, gender, sum(count) as total FROM gender_count group by class_id , gender;")) {

        while (rs.next()) {
            stats.add(new Class_GenderS(rs.getString("class_id"), rs.getString("gender"), rs.getInt("total")));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }



    return stats;
}



    private static class Class_GenderS {
        private String class_id;
        private String gender;
        private int count;

        public Class_GenderS(String class_id, String gender, int count) {
            this.gender = gender;
            this.class_id = class_id;
            this.count = count;
        }

        public String getGender() { return gender; }
        public String getClass_id() { return class_id; }
        public int getCount() { return count; }
    }
}
